package huv.andlogin;



import java.io.DataOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map.Entry;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

public class AutoLogin {

	
	static final int _CONNECTION_COMPLETE = 0;
	static final int _INVALID_URL = 1;
	static final int _UNABLE_OPEN_CONNECTION = 2;
	static final int _NO_SUCH_ALGORITHM = 3;
	static final int _KEY_MANAGMENT_ERROR = 4;
	static final int _PROTOCOL_ERROR = 5;
	static final int _IO_ERROR = 6;
	static final int _DATA_OUTPUT_STREAM_INIT_ERROR = 7; 
	static final int _WRITE_BYTE_ERROR = 8;
	static final int _CONNECTION_CLOSE_ERROR = 9;
	static int login(String url, Iterator<Entry<String, String>> requestProperty, String postRequest){
		URL _url;
		try {
			 _url = new URL(url);
		} catch (MalformedURLException e) {
			return _INVALID_URL;
		}
		SSLContext sslcontext;
		try {
			sslcontext = SSLContext.getInstance("TLS");
		} catch (NoSuchAlgorithmException e1) {
			return _NO_SUCH_ALGORITHM;
		}
		try {
			sslcontext.init(null, null, null);
		} catch (KeyManagementException e1) {
			return _KEY_MANAGMENT_ERROR;
		}
		HttpsURLConnection httpsurlconnection;
		HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
		try{
			httpsurlconnection = (HttpsURLConnection)_url.openConnection();
		}catch(Exception e){
			return _UNABLE_OPEN_CONNECTION;
		}
		httpsurlconnection.setDoOutput(true);
		httpsurlconnection.setDoInput(true);
		try {
			httpsurlconnection.setRequestMethod("POST");
		} catch (ProtocolException e) {
			return _PROTOCOL_ERROR;
		}
		while(requestProperty.hasNext()){
			Entry<String,String> t = requestProperty.next();
			String key = t.getKey();
			String value = t.getValue();
			httpsurlconnection.setRequestProperty(key,value);
		}
		httpsurlconnection.setRequestProperty("Content-length",String.valueOf(postRequest.length()));
		DataOutputStream out;
		try {
			out = new DataOutputStream(httpsurlconnection.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return _DATA_OUTPUT_STREAM_INIT_ERROR;
		}
		try {
			
			out.writeBytes(postRequest);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return _WRITE_BYTE_ERROR;
		}
		try {
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return _CONNECTION_CLOSE_ERROR;
		}
		httpsurlconnection.disconnect();
					
		return _CONNECTION_COMPLETE;
		
	}
	@SuppressWarnings("unchecked")
	static int login(Cfg c){
		return login(c.getUrl(),(Iterator<Entry<String, String>>) c.getRPIterator(),c.getPostString());
	}
}
